using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;
using System.Text;
using System.Xml;

public partial class Manager_ProductStore_InputStore : System.Web.UI.Page
{
    protected object sData = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["AdminUserID"] == null)
        {
            Response.Write("<script language=javascript>alert('Time is out.');window.open('../Default.aspx','_top');</script>");
            return;
        }
        fnSearch();
        if (!IsPostBack)
        {
            GetStore();
            BindData();
        }
        else
        {
            if (hidXML.Value.Trim() != "")
            {
                PccMsg myMsg = new PccMsg(hidXML.Value);
                if (myMsg.Query("Method") == "LOADDATA")
                {
                    BindData();
                    hidXML.Value = "";
                }
                else if (myMsg.Query("Method") == "SAVE")
                {
                    SaveData(myMsg);
                    hidXML.Value = "";
                }
                else if (myMsg.Query("Method") == "DELETE")
                {
                    string StDID = myMsg.Query("StDID");
                    DeleteData(StDID);
                    hidXML.Value = "";
                }
                else if (myMsg.Query("Method") == "LOADDISTRIBUTIONCOMPANY")
                {
                    string DisCompID = myMsg.Query("DisCompID");
                    LOADDISTRIBUTIONCOMPANY(DisCompID);
                    hidXML.Value = "";
                }
            }
        }
    }


    private void LOADDISTRIBUTIONCOMPANY(string DisCompID)
    {
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("DisCompID", DisCompID);
        clsWebShop cls = new clsWebShop();
        DataTable dt = null;
        dt = cls.Get_DistributionCompanyByCondition(msg.GetXmlStr).Tables[0];

        if (dt.Rows.Count > 0)
        {
            ViewState["DisCompID"] = DisCompID;
            txtHoTen.Text = dt.Rows[0]["Name"].ToString();
            txtDiaChi.Text = dt.Rows[0]["Address"].ToString();
            txtTaxNo.Text = dt.Rows[0]["TaxNo"].ToString();
            txtDienThoai.Text = dt.Rows[0]["Phone"].ToString().Trim();
            txtNote.Text = dt.Rows[0]["Note"].ToString();
            BindData();
        }
    }

    #region Store
    private void fnSearch()
    {
        clsWebShop cls = new clsWebShop();
        DataTable dt;
        dt = cls.GetData("select rtrim(PDName)PDName,PDID from Product p inner join Catalogue c  on p.catid=c.catid where PDName like N'%" + Request.QueryString["q"] + "%'  and p.Status<>'D'  " + " and c.KindNo='P' and c.Status<>'D'").Tables[0];
        sData = CreateJsonParameters(dt);
    }
    public string CreateJsonParameters(DataTable dt)
    {
        StringBuilder JsonString = new StringBuilder();

        //Exception Handling
        if (dt != null && dt.Rows.Count > 0)
        {

            JsonString.Append("[ ");

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                JsonString.Append("{ ");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (j < dt.Columns.Count - 1)
                    {
                        JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() +
                              "\":" + "\"" +
                              dt.Rows[i][j].ToString() + "\",");
                    }
                    else if (j == dt.Columns.Count - 1)
                    {
                        JsonString.Append("\"" +
                           dt.Columns[j].ColumnName.ToString() + "\":" +
                           "\"" + dt.Rows[i][j].ToString() + "\"");
                    }
                }

                /*end Of String*/
                if (i == dt.Rows.Count - 1)
                {
                    JsonString.Append("} ");
                }
                else
                {
                    JsonString.Append("}, ");
                }
            }

            JsonString.Append("]");
            return JsonString.ToString();
        }
        else
        {
            return null;
        }
    }
    #endregion

    private void GetStore()
    {
        clsWebShop cls = new clsWebShop();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("StID", "");
        DataTable dt = cls.Get_StoreByCondition(msg.GetXmlStr).Tables[0];
        ViewState["dtStore"] = dt;

        clsCommon clsCom = new clsCommon();
        lblRateToday.Text = clsCom.FormatMoney(cls.GetMoney("USD").ToString());
        Calendar1.Text = DateTime.Now.ToString("yyyy/MM/dd");
    }

    private void BindData()
    {
        clsWebShop cls = new clsWebShop();

        DataTable dt = cls.GetData("select * from StoreMain where InputDate='" + Calendar1.Text.Replace("/", "") + "'").Tables[0];
        if (dt.Rows.Count > 0)
        {
            ViewState["StM"] = dt.Rows[0]["StM"].ToString();
        }
        else
        {
            ViewState["StM"] = null;
        }

        string DisCompID = "0";
        if (ViewState["DisCompID"] != null)
            DisCompID = ViewState["DisCompID"].ToString();

        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("StID","0");
        msg.CreateFirstNode("StartDate", Calendar1.Text.Replace("/", ""));
        msg.CreateFirstNode("EndDate", Calendar1.Text.Replace("/", ""));
        msg.CreateFirstNode("DisCompID", DisCompID);
        DataTable dt1 = cls.Get_StoreDetailByCondition(msg.GetXmlStr).Tables[0];
        if (dt1.Rows.Count <= 0)
        {
            DataRow dr = dt1.NewRow();
            dt1.Rows.Add(dr);
        }


        grvMaster.DataSource = dt1;
        grvMaster.DataBind();
    }
    protected void grvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlStore = (DropDownList)e.Row.FindControl("ddlStore");
            ddlStore.DataSource = (DataTable)ViewState["dtStore"];
            ddlStore.DataTextField = "StName";
            ddlStore.DataValueField = "StID";
            ddlStore.DataBind();
            HtmlInputHidden hidPDID = (HtmlInputHidden)e.Row.FindControl("hidPDID");

            if (ViewState["StM"] != null)
            {
                clsCommon clsCom = new clsCommon();
                DropDownList ddlRate = (DropDownList)e.Row.FindControl("ddlRate");
                TextBox txtPDName = (TextBox)e.Row.FindControl("txtPDName");
                TextBox txtQuantity = (TextBox)e.Row.FindControl("txtQuantity");
                TextBox txtPrice = (TextBox)e.Row.FindControl("txtPrice");
                Label lblTotal = (Label)e.Row.FindControl("lblTotal");
                HtmlInputHidden hidStDID = (HtmlInputHidden)e.Row.FindControl("hidStDID");

                string StID = DataBinder.Eval(e.Row.DataItem, "StID").ToString();
                string InputRate = DataBinder.Eval(e.Row.DataItem, "InputRate").ToString();
                string PDName = DataBinder.Eval(e.Row.DataItem, "PDName").ToString();
                string PDID = DataBinder.Eval(e.Row.DataItem, "PDID").ToString();
                string Quantity = DataBinder.Eval(e.Row.DataItem, "Quantity").ToString();
                string InputPrice = DataBinder.Eval(e.Row.DataItem, "InputPrice").ToString();
                string Total = DataBinder.Eval(e.Row.DataItem, "Total").ToString();
                string StDID = DataBinder.Eval(e.Row.DataItem, "StDID").ToString();

                try { ddlStore.Items.FindByValue(StID).Selected = true; }
                catch { }
                try { ddlRate.Items.FindByValue(InputRate).Selected = true; }
                catch { }
                txtPDName.Text = PDName;
                hidPDID.Value = PDID;
                txtQuantity.Text = Quantity;
                txtPrice.Text = InputPrice;
                lblTotal.Text = Total;
                hidStDID.Value = StDID;

                txtPrice.Text = clsCom.FormatMoney(txtPrice.Text);
                lblTotal.Text = clsCom.FormatMoney(lblTotal.Text);
            }

            if (hidPDID.Value != "")
            {
                TextBox txtPDName = (TextBox)e.Row.FindControl("txtPDName");
                txtPDName.Style.Add("background-color", "LightGoldenrodYellow");
            }
        }
    }

    private void DeleteData(string ID)
    {
        clsWebShop cls = new clsWebShop();
        cls.UpdateData("Delete from StoreDetail where StDID=" + ID);
        BindData();
    }

    private void SaveData(PccMsg myMsg)
    {
        clsWebShop cls = new clsWebShop();
        string DisCompID = ViewState["DisCompID"].ToString();
        string StM = "0";
        if (ViewState["StM"] != null && ViewState["StM"].ToString() != "")
        {
            StM = ViewState["StM"].ToString();
        }
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("StM", StM);
        msg.CreateFirstNode("DisCompID", DisCompID);
        msg.CreateFirstNode("InputDate", Calendar1.Text.Replace("/", "")+DateTime.Now.ToString("hhmmss"));
        msg.CreateFirstNode("USD", lblRateToday.Text.Replace(",", ""));
        msg.CreateFirstNode("UserID", Session["AdminUserID"].ToString());
        string xmlReturn = cls.Ins_Upd_StoreMain(msg.GetXmlStr);
        msg = new PccMsg(xmlReturn);
        string StMOut = msg.Query("strStMOut");
        if (StMOut.Length > 0 && myMsg.GetXmlStr.Length > 0 && StMOut != "0")
        {
            XmlNodeList node = myMsg.QueryNodes("StoreDetail");

            for (int i = 0; i < node.Count; i++)
            {
                myMsg = new PccMsg();
                string StDID = "0";
                if (node[i].SelectSingleNode("StDID").InnerText.Length > 0 && node[i].SelectSingleNode("StDID").InnerText != "0")
                    StDID = node[i].SelectSingleNode("StDID").InnerText;

                myMsg.CreateFirstNode("StDID", StDID);
                myMsg.CreateFirstNode("StM", StMOut);
                myMsg.CreateFirstNode("PDID", node[i].SelectSingleNode("PDID").InnerText);
                myMsg.CreateFirstNode("StID", node[i].SelectSingleNode("StID").InnerText);
                myMsg.CreateFirstNode("Quantity", node[i].SelectSingleNode("Quantity").InnerText.Replace(",", ""));
                myMsg.CreateFirstNode("InputPrice", node[i].SelectSingleNode("InputPrice").InnerText.Replace(",", ""));
                myMsg.CreateFirstNode("InputRate", node[i].SelectSingleNode("InputRate").InnerText);
                myMsg.CreateFirstNode("Total", node[i].SelectSingleNode("Total").InnerText.Replace(",", ""));
                myMsg.CreateFirstNode("UserID", Session["AdminUserID"].ToString());
                cls.Ins_Upd_StoreDetail(myMsg.GetXmlStr);
            }
        }
        BindData();
    }
}
